#!/usr/bin/env python 
# -*- coding:utf-8 -*-

from os import path
from queue import Queue
from threading import Thread,Lock
from lib.utils.check import *
from lib.utils.printer import *
from lib.utils.readfile import *
from lib.request.request import *
from lib.utils.settings import T_MAX,NOW,PARAMS_PATH
from urllib.error import HTTPError
import time

global_isNothing = True
global_result = []
class params(Request):
    """
    检测隐藏参数
    """
    def __init__(self,kwargs,url,data):
        Request.__init__(self,kwargs,url,data)
        self.url = url
        self.data = data
    
    def check(self):
        info("检测可能的隐藏参数...")
        queue = Queue(T_MAX)
        for _ in range(T_MAX):
            thread = ThreadBrute(self.url,queue,self)
            thread.daemon = True
            thread.start()
        for path in readfile(PARAMS_PATH):
            queue.put(path.decode("utf-8"))
        queue.join()

class ThreadBrute(Thread):
    get = "GET"
    def __init__(self,target,queue:Queue,request:Request):
        Thread.__init__(self)
        self.queue = queue
        self.target = target
        self.request = request
    def check(self):
        global global_isNothing
        global global_result
        while True:
            try:
                splitUrl = SplitUrl(self.target)
                netlocUrl = splitUrl.netloc
                req_1 = self.request.Send(url=self.target,method=self.get)
                q = self.queue.get()
                url = Cquery(req_1.url,q)
                more("检测载荷:{}".format(url))
                req_2 = self.request.Send(url=url,method=self.get)
                if req_2.code in range(200,399):
                    if len(req_1.content) != len(req_2.content):
                        global_result.append('[{}] [{}]'.format(req_2.code,Cparams(req_2.url)))
                        global_isNothing = False
            except Exception as e:
                pass
            except AttributeError as e:
                pass
            except TypeError as e:
                pass
            finally:
                self.queue.task_done()
    def run(self):
        self.check()
def run(kwargs,url,data):
    result = {
        'params':None
    }
    scan = params(kwargs,url,data)
    scan.check()
    if global_isNothing:
        info_nothing()
    else:
        if global_result:
            for r in global_result:
                plus('疑似找到敏感参数: {}'.format(r))
                if not result['params']:
                    result['params'] = r
                else:
                    result['params'] += " ," + r
    return result